package com.xqh.service.impl.ques;

import com.alibaba.fastjson.JSONArray;
import com.xqh.base.dao.CrudMapper;
import com.xqh.base.exception.ServiceException;
import com.xqh.base.service.impl.BaseCrudServiceImpl;
import com.xqh.base.util.id.IdWorker;
import com.xqh.base.util.serializer.ObjectUtils;
import com.xqh.dao.ques.QuesTypeMapper;
import com.xqh.entity.ques.QuesType;
import com.xqh.service.ques.QuesTypeService;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author leo
 * @date 2018-04-18 12:24:39
 * @version 1.0.0
 * @copyright www.vip-young.com
 */
@Service("quesTypeService")
public class QuesTypeServiceImpl extends BaseCrudServiceImpl<QuesType> implements QuesTypeService {

    @Resource
    private QuesTypeMapper quesTypeMapper;

    @Override
    public CrudMapper init() {
        return quesTypeMapper;
    }

    @Override
    public JSONArray treeData(QuesType type) {
        List<QuesType> typeList = quesTypeMapper.selectByParams(ObjectUtils.changeToMap(type));
        JSONArray resArray = ObjectUtils.wrapperGetTreeData(typeList);
        return ObjectUtils.setTreeHomeNode(resArray);
    }


    @Override
    public QuesType getByLongCode(String longCode) {
        Map<String,Object> map = new HashMap<>();
        map.put("longCode", longCode);
        QuesType type = this.findOneByBiz(map);
        return type;
    }

    @Override
    @Transactional
    public int saveData(QuesType entity) throws ServiceException {
        Assert.notNull(entity, "参数不能为空");
        if(null != entity.getId()){
            QuesType old = quesTypeMapper.selectByPrimaryKey(entity.getId());
            old.setName(entity.getName());
            old.setDescription(entity.getDescription());
            return quesTypeMapper.updateByPrimaryKey(old);
        }else{
            entity.setCode(IdWorker.getStringCode());
            if(StringUtils.hasText(entity.getParentCode())){
                Map<String,Object> map = new HashMap<>();
                map.put("code", entity.getParentCode());
                QuesType parent = this.findOneByBiz(map);
                entity.setLevel(parent.getLevel()+1);
                entity.setLongCode(parent.getLongCode().concat(",").concat(entity.getCode()));
            }else{
                entity.setLevel(1);
                entity.setLongCode(entity.getCode());
            }
            return quesTypeMapper.insert(entity);
        }
    }
}